class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == nullptr || head->next == nullptr) return head;
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* prev = dummy;
        ListNode* cur = head;
        bool repeat = false;
        while (cur && cur->next) {
            if (cur->val == cur->next->val) {
                cur->next = cur->next->next;
                repeat = true;
            }
            else {
                if (repeat == true) {
                    prev->next = cur->next;
                    repeat = false;
                } 
                else prev = cur;
                cur = cur->next;
            }
        }
        if (repeat == true) {
            prev->next = cur->next;
        } 
        ListNode* res = dummy->next;
        delete dummy;
        return res;
    }
};